#!/usr/bin/env python
#coding=utf-8

from __future__ import division
import time
import sys
from define import BASE_DIR
sys.path.append(BASE_DIR)

#import pymongo
from lib.abstract_cron import abstract_cron
from lib.func_ext import dateTypeInterval,str2sec,sec2str,ksort

#需要修改
class business_api_month(abstract_cron) :

    #需要修改
    noLock = True   #是否生成脚本锁文件
    selectTable = 'sdb_statistics_business_api_day'
    insertTable = 'sdb_statistics_business_api_month'

    def __init__(self) :
        #需要修改
        super(business_api_month,self).__init__(__file__)
        self.lastMonth = dateTypeInterval('last_month')
        self.currentMonth = dateTypeInterval('month')
        self.dateIdent = '%s/%s' % (self.currentMonth[0],self.currentMonth[1])
        self.monthFormat = '%s/%s' % (self.lastMonth[0],self.lastMonth[1])

    def boot(self,timestamp={}) :
        #self.preBoot()

        data = self.getData(timestamp)
        if data :
            for v in data :
                v['month'] = self.monthFormat
                v['calltime'] = str2sec(self.lastMonth[1],'%Y-%m-%d')-1*24*3600
                #计算成功率
                v['sum_fail'] = v['sum'] - v['sum_succ']
                self.figureRatio(v,'sum','sum_fail','api_succ_ratio')
                #数据过滤
                self.filterItems(v)

            #批量插入
            self.doBatchExec()

        self.sufBoot()
        print 'ok'

    def getData(self,timestamp=[]) :
        timeFilter = self.getTimeFilter(timestamp)
        sql = 'SELECT `from_node_id`,`from_node_type`,`to_node_id`,`to_node_type`,'
        sql += ' SUM(`sum`) AS sum,SUM(`sum_succ`) AS sum_succ,`api`'
        sql += ' FROM '+self.selectTable
        sql += ' WHERE '+self.db._filter(timeFilter)
        sql += ' GROUP BY `from_node_id`,`to_node_id`,`api`'
        row = self.db.select(sql)
        return row

    def getTimeFilter(self,timestamp=[]) :
        keyFilter = {}
        time_begin = str2sec(self.lastMonth[0],'%Y-%m-%d')
        time_end = str2sec(self.lastMonth[1],'%Y-%m-%d')+1*24*3600
        keyFilter['calltime|between'] = timestamp and timestamp or [time_begin,time_end]
        return keyFilter

    def insertKeys(self) :
        return ['from_node_id','from_node_type','to_node_id',
                'to_node_type','sum','sum_succ','api_succ_ratio'
                ,'api','month','calltime','sum_fail']


if __name__ == '__main__' :
    obj = business_api_month()
    obj.boot()